package com.fizz.oauth.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //校验客户端
        //获取身份信息
        RequestContext rq = RequestContext.getCurrentContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!(authentication instanceof OAuth2Authentication)){
            return null;
        }
        OAuth2Authentication auth2Authentication = ((OAuth2Authentication) authentication);
        //获取权限
        Authentication userAuthentication = auth2Authentication.getUserAuthentication();
        String principal = userAuthentication.getName();
        List<String> authorites =new ArrayList<>();
        userAuthentication.getAuthorities().stream().forEach(c->authorites.add(c.getAuthority()));
        OAuth2Request oAuth2Request = auth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String,Object> jsonMap = new HashMap<>();
        if(userAuthentication != null){
            jsonMap.put("principal", principal);
            jsonMap.put("authorities", authorites);
        }

        rq.addZuulRequestHeader("json-token", JSON.toJSONString(jsonMap));
        return null;
    }
}
